package com.example.asus.graceplayer.http;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by asus on 2018/10/24.
 */
public class LrcFileDownLoad {
    public static final String LRC_SEARCH_URL = "http://geci.me/api/lyric/";                //歌词API
    private static final int REQUEST_TIMEOUT = 15 * 1000;                    //设置请求超时15秒钟
    private static final int SO_TIMEOUT = 15 * 1000;                            //设置等待数据超时时间15秒钟

    public static String getSongLRCUrl(String path, String songName)
            throws Exception {
        String url = null;
        String str_json = null;

        //歌词名为空返回null
        if (songName == null) {
            return null;
        }
        String name = URLEncoder.encode(songName, "UTF-8");                //编码转换
        str_json = getHtmlCode(path + name);

        //超时以及其他异常时返回null
        if (str_json == null) return null;

        JSONObject jsonObject = new JSONObject(str_json);
        int count = jsonObject.getInt("count");

        //没有歌词时返回null
        if (count == 0) {
            return null;
        }

        // 获取得到是歌词url列表，这里只取第一个歌词的url
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        JSONObject item = jsonArray.getJSONObject(0);

        url = item.getString("lrc");
        return url;
    }

    // 获取网页源码
    public static String getHtmlCode(String url) {
        String responseData = null;
        OkHttpClient client=new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15,TimeUnit.SECONDS)
                .build();
        Request request=new Request.Builder()
                .url(url)
                .build();
        try{
            Response response=client.newCall(request).execute();
            responseData=response.body().string();
            return responseData;
        }catch (IOException e){
            e.printStackTrace();
            if(e instanceof SocketTimeoutException){//超时异常
                System.out.println("ConnectException timeout");
            }
        }
        return responseData;
    }
}
